from flask_sqlalchemy import SQLAlchemy
import pandas as pd
import numpy as np
from scipy.spatial.distance import pdist, euclidean
from sklearn.datasets import load_iris

db = SQLAlchemy()


def read_csv_file(file_path):
    # 读取表头
    head_row = pd.read_csv(file_path, nrows=0)
    # print(list(head_row))
    # 表头列转为 list
    head_row_list = list(head_row)

    # 读取
    csv_result = pd.read_csv(file_path, usecols=head_row_list)
    row_list = csv_result.values.tolist()
    # print(f"行读取结果：\n{np.array(row_list)}")
    col_obj = csv_result.T
    col_list = col_obj.values.tolist()
    # print(f"行转列读取结果：\n{np.array(col_list)}")
    return head_row_list, row_list, col_list


def list_to_csv(list_data, write_path):
    df = pd.DataFrame(list_data)
    df.to_csv(write_path)


def DaviesBouldin(X, labels):
    n_cluster = len(np.bincount(labels))
    cluster_k = [X[labels == k] for k in range(n_cluster)]
    centroids = [np.mean(k, axis=0) for k in cluster_k]

    # 求S
    S = [np.mean([euclidean(p, centroids[i]) for p in k]) for i, k in enumerate(cluster_k)]
    Ri = []

    for i in range(n_cluster):
        Rij = []
        # 计算Rij
        for j in range(n_cluster):
            if j != i:
                r = (S[i] + S[j]) / euclidean(centroids[i], centroids[j])
                Rij.append(r)
        # 求Ri
        Ri.append(max(Rij))

        # 求dbi
    dbi = np.mean(Ri)

    return dbi


if __name__ == '__main__':
    head_row_list, row_list, col_list = read_csv_file("static/csv/gaojia.csv")
    print(head_row_list)
    print(col_list)
    list_to_csv(row_list, "test.csv")
